package com.leqicheng.tenon.login;

import java.util.HashMap;
import java.util.Map;

import org.apache.cordova.CallbackContext;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.leqicheng.tenon.RuntimeActivity;
import com.leqicheng.tenon.R;
import com.leqicheng.tenon.log.GetLogIdHttpRequest;
import com.leqicheng.tenon.log.LogHertbeatPost;
import com.leqicheng.tenon.login.weibo.AccessTokenKeeper;
import com.leqicheng.tenon.login.weibo.AuthListener;
import com.leqicheng.tenon.login.weibo.WeiboConstants;
import com.leqicheng.tenon.login.weixin.WeixinConstants;
import com.leqicheng.tenon.model.EntryInfoModel;
import com.leqicheng.tenon.util.OrientationEnum;
import com.leqicheng.tenon.util.RequestStatus;
import com.leqicheng.tenon.util.RequestTypeEnum;
import com.leqicheng.tenon.util.SerializableMap;
import com.leqicheng.tenon.util.TenonDB;
import com.leqicheng.tenon.util.WindowStatusCode;
import com.sina.weibo.sdk.auth.AuthInfo;
import com.sina.weibo.sdk.auth.sso.SsoHandler;
import com.tencent.mm.sdk.modelmsg.SendAuth;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;

public class PopLoginWindow extends PopWindow implements OnClickListener {

    private final LayoutInflater mInflater;
    private final Context mContext;
    private final PopupWindow mPopupWindow;
    private final LinearLayout mLayoutParent;
    private RelativeLayout mWeiXinButton;
    private AuthInfo mAuthInfo;
    private IWXAPI mIWXAPI;
    private PopWindow mPopWindowContext;
    private Handler mHandler;
    private TenonDB mTenonDB;
    private RelativeLayout mWeiboButton;
    private ImageButton mCloseWindowButton;
    private static final String SCOPE = "get_user_info, get_simple_userinfo, add_share";
    static Handler mLogHandler = new Handler();
    Runnable mLogRunnable = new Runnable() {
        @Override
        public void run() {
            // 要做的事情
            if (!EntryInfoModel.getInstance().getLogId().equals("0")) {
                if ("".equals(EntryInfoModel.getInstance().getTenonUserId())
                        || EntryInfoModel.getInstance().getTenonUserId() != null) {
                    LogHertbeatPost logHertbeatPost = new LogHertbeatPost(
                            mContext, null);
                    logHertbeatPost.postRequest(EntryInfoModel.getInstance());
                }
            }
            mLogHandler.postDelayed(this, 30000);
        }
    };

    public PopLoginWindow(Context context, Handler handler) {
        super();
        this.mContext = context;
        mPopWindowContext = this;
        mHandler = handler;
        this.mInflater = (LayoutInflater) this.mContext
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View layout = this.mInflater.inflate(R.layout.popwindow_login, null);
        this.mLayoutParent = (LinearLayout) layout
                .findViewById(R.id.parent_layout);
        mWeiXinButton = (RelativeLayout) layout
                .findViewById(R.id.relative_weixin);
        mWeiXinButton.setOnClickListener(this);
        mWeiboButton = (RelativeLayout) layout
                .findViewById(R.id.relatvie_weibo);
        mWeiboButton.setOnClickListener(this);
        mCloseWindowButton = (ImageButton) layout
                .findViewById(R.id.close_window);
        mCloseWindowButton.setOnClickListener(this);
        this.mPopupWindow = new PopupWindow(layout);
        this.mPopupWindow.setFocusable(true);

        // 控制popupwindow的宽度和高度自适应
        this.mLayoutParent.measure(View.MeasureSpec.UNSPECIFIED,
                View.MeasureSpec.UNSPECIFIED);
        this.mPopupWindow.setWidth(this.mLayoutParent.getMeasuredWidth() + 6);
        this.mPopupWindow.setHeight(this.mLayoutParent.getMeasuredHeight() + 6);

        this.mTenonDB = new TenonDB(mContext);
        EntryInfoModel model = EntryInfoModel.getInstance();
        String tenonUserIdFromDB = this.mTenonDB.count(model.getChannelId(),
                model.getGameId());
        if (tenonUserIdFromDB != null) {
            model.setTenonUserId(tenonUserIdFromDB);
            Toast.makeText(mContext, "登陆成功", Toast.LENGTH_SHORT).show();
            String[] tenonUserInfo = mTenonDB
                    .getTenonUserInfo(tenonUserIdFromDB);
            GetLogIdHttpRequest getLogIdHttpRequest = new GetLogIdHttpRequest(
                    mContext, this);
            getLogIdHttpRequest.postRequest(model);
            handleLoginMessage(createDataMap(tenonUserIdFromDB, tenonUserInfo),
                    true);
        }
    }

    private void handleLoginMessage(Map<String, Object> dataMap, boolean success) {
        Message msg = new Message();
        msg.what = WindowStatusCode.LOGIN_WINDOW_SUCCEED;
        msg.arg1 = 1;
        msg.obj = dataMap;
        mHandler.sendMessage(msg);
    }

    private Map<String, Object> createDataMap(String tenonUserIdFromDB,
            String[] tenonUserInfo) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("tenonUserID", tenonUserIdFromDB);
        map.put("username", tenonUserInfo[0]);
        map.put("avatar", tenonUserInfo[1]);
        map.put("sex", tenonUserInfo[2]);
        return map;
    }

    public PopupWindow getPopupWindow() {
        return this.mPopupWindow;
    }

    @Override
    public void onClick(View v) {
        
        if(v.getId() == R.id.relatvie_weibo) {
            registerWeiboBroadcast();
            this.mAuthInfo = new AuthInfo(mContext, WeiboConstants.APP_KEY,
                    WeiboConstants.REDIRECT_URL, WeiboConstants.SCOPE);
            RuntimeActivity.mSsoHandler = new SsoHandler((Activity) mContext,
                    this.mAuthInfo);
            RuntimeActivity.mSsoHandler.authorize(new AuthListener(this.mContext));
            AccessTokenKeeper.readAccessToken(this.mContext);
            Toast.makeText(mContext, "正在跳转微博登陆", Toast.LENGTH_SHORT).show();
        } else if(v.getId() == R.id.relative_weixin) {
            registerWeixinBroadcast();
            this.mIWXAPI = WXAPIFactory.createWXAPI(mContext,
                    WeixinConstants.APP_ID, false);
            this.mIWXAPI.registerApp(WeixinConstants.APP_ID);
            if (this.mIWXAPI.isWXAppInstalled()) {
                final SendAuth.Req req = new SendAuth.Req();
                req.scope = "snsapi_userinfo";
                req.state = "wechat_sdk_demo_test";
                this.mIWXAPI.sendReq(req);
                Toast.makeText(mContext, "正在跳转微信登陆", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(mContext, "请先安装微信应用", Toast.LENGTH_SHORT).show();
            }
        } else if(v.getId() == R.id.close_window) {
            Message msg = new Message();
            msg.what = WindowStatusCode.LOGIN_WINDOW_SUCCEED;
            mHandler.sendMessage(msg);
        }
    }

    private void registerWeiboBroadcast() {
        IntentFilter intentFilter = new IntentFilter();

        intentFilter.addAction("weibo success"); // 为BroadcastReceiver指定action，即要监听的消息名字。

        BroadcastReceiver myBroadcastReceiver = new BroadcastReceiver() {

            @Override
            public void onReceive(Context context, Intent intent) {
                mContext.unregisterReceiver(this);
                EntryInfoModel model = EntryInfoModel.getInstance();
                WeiboLoginHttpRequest weiboLoginHttpRequest = new WeiboLoginHttpRequest(
                        mContext, mPopWindowContext);
                weiboLoginHttpRequest.postRequest(model);
            }
        };
        mContext.registerReceiver(myBroadcastReceiver, intentFilter); // 注册监听
    }

    private void registerWeixinBroadcast() {
        IntentFilter intentFilter = new IntentFilter();

        intentFilter.addAction("weixin complete"); // 为BroadcastReceiver指定action，即要监听的消息名字。

        BroadcastReceiver myBroadcastReceiver = new BroadcastReceiver() {

            @Override
            public void onReceive(Context context, Intent intent) {
                mContext.unregisterReceiver(this);
                // TODO Auto-generated method stub
                // mCallbackContext.success("weixin success");
                if (intent.getBooleanExtra("login_status", false)) {
                    EntryInfoModel model = EntryInfoModel.getInstance();
                    WeixinLoginHttpRequest weixinLoginHttpRequest = new WeixinLoginHttpRequest(
                            mContext, mPopWindowContext);
                    weixinLoginHttpRequest.postRequest(model);
                }
            }
        };
        mContext.registerReceiver(myBroadcastReceiver, intentFilter); // 注册监听
    }

    @Override
    public void onComplete(RequestTypeEnum requestType, int status,
            String responseBody) {
        EntryInfoModel model = EntryInfoModel.getInstance();
        switch (status) {
        case RequestStatus.NETWORK_ERROR:
            Toast.makeText(mContext, "网络错误", Toast.LENGTH_SHORT).show();
            break;
        case RequestStatus.OBTAIN_SUCCESS:
            switch (requestType) {
            case LOGIN:
                String TenonUserId = JSON.parseObject(responseBody).getString(
                        "user_id");
                String TenonUserName = JSON.parseObject(responseBody)
                        .getString("name");
                String TenonUserIconUrl = JSON.parseObject(responseBody)
                        .getString("image_url");
                String TenonUserSex = JSON.parseObject(responseBody).getString(
                        "sex");
                model.setTenonUserId(TenonUserId);
                model.setTenonUserName(TenonUserName);
                model.setTenonUserIconUrl(TenonUserIconUrl);
                model.setTenonUserSex(TenonUserSex);
                GetLogIdHttpRequest getLogIdHttpRequest = new GetLogIdHttpRequest(
                        mContext, this);
                getLogIdHttpRequest.postRequest(model);
                insertInTenonDB(model);
                String[] tenonUserInfo = { model.getTenonUserName(),
                        model.getTenonUserIconUrl(), model.getTenonUserSex() };
                // org.json.JSONObject userInfoInJson = new org.json.JSONObject(
                // map);
                handleLoginMessage(
                        createDataMap(model.getTenonUserId(), tenonUserInfo),
                        true);
                break;
            case GET_LOG_ID:
                String LogId = JSON.parseObject(responseBody).getString(
                        "log_id");
                model.setLogId(LogId);
                mLogHandler.removeCallbacks(mLogRunnable);
                mLogHandler.postDelayed(mLogRunnable, 10000);
                break;
            }
            break;
        default:
            Toast.makeText(mContext, "登陆失败", Toast.LENGTH_SHORT).show();
            break;
        }
    }

    private void insertInTenonDB(EntryInfoModel model) {
        this.mTenonDB = new TenonDB(mContext);
        mTenonDB.insert(model.getTenonUserId(), model.getChannelId(),
                model.getGameId(), model.getTenonUserName(),
                model.getTenonUserIconUrl(), model.getTenonUserSex());
    }
}
